import React, { useState } from 'react'
import CommonTable from '@/common/CommonTable'
import { tableConfig, dataSource, actions } from './config'
import _ from 'lodash'

const UnInvertTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [selectedParentRowKeys, setSelectedParentRowKeys] = useState([])
  const checkBoxSelection = (data) => {
    return _.map(data, (item, key) => {
      if (item.children) {
        return _.flatten(checkBoxSelection(item.children))
      } else {
        return item.id
      }
    })
  }
  const fatherRowRender = (data, row) => {
    const fahterRow = _.uniq(
      _.map(row, (item) => {
        return item.parentId
      })
    )
    return _.map(data, (item) => {
      if (item.id !== fahterRow[fahterRow.length - 1]) {
        return _.flatten(fatherRowRender(item.children, row))
      } else {
        return { ...item }
      }
    })
  }
  const handlerUnInvert = () => {
    setSelectedRowKeys(
      _.difference(
        _.flatten(checkBoxSelection(selectedParentRowKeys)),
        selectedRowKeys
      )
    )
  }
  const actionsClick = {
    unInvert: () => handlerUnInvert(),
  }
  const tableProps = {
    columns: tableConfig,
    dataSource,
    rowKey: 'id',
    actions: _.map(actions, (item, key) => {
      const obj = { ...item }
      obj.onClick = actionsClick[item.id]
      return obj
    }),
    rowSelection: {
      selectedRowKeys,
      checkStrictly: false,
      onChange: (val, row) => {
        _.uniq(
          _.map(row, (item, key) => {
            if (_.indexOf(val, item.parentId) === -1) {
              setSelectedParentRowKeys(
                _.flatten(fatherRowRender(dataSource, row))
              )
            } else {
              setSelectedParentRowKeys(dataSource)
            }

            return
          })
        )
        setSelectedRowKeys(val)
      },
    },
  }
  return (
    <div>
      <CommonTable {...tableProps} />
    </div>
  )
}

export default UnInvertTable
